import { MessageCode } from '@/interface'
import { addSmySign } from '@/utils/common'
import { openWeb, validateAuth } from './hooks'
import { messageMap } from './useOnMsg'

// 小程序携带参数初始化
export const useTakeParamsLaunchMini = async (options: any) => {
  const serverOptions = options
  Object.keys(serverOptions).map((key: keyof typeof serverOptions) => {
    // 解码防止携带encodeURIComponent参数
    Object.assign(serverOptions, {
      [key]: decodeURIComponent(serverOptions[key]),
    })

    // 数字字符串转number类型
    const numRule = /^[0-9]{1,}$/g

    if (options[key] && numRule.test(options[key] as string)) {
      Object.assign(serverOptions, { [key]: +serverOptions[key] })
    }

    if (serverOptions[key] === 'null') {
      Object.assign(serverOptions, { [key]: 0 })
    }
  })

  console.log('打开服务参数：', serverOptions)
  // 扫码打开小程序 问卷
  if (serverOptions.q) {
    serverOptions.url = addSmySign(serverOptions.q)
    const userInfo = uni.getStorageSync('userInfo') || null
    try {
      await validateAuth()
      return messageMap[MessageCode.VALIDATE_AUTH]({
        ...serverOptions,
        authType: 1,
        sensitiveType: (userInfo && +userInfo.level === 2 && 1) || 0,
      })
    } catch (e) {
      //TODO handle the exception
    }
  }

  if (serverOptions.url) {
    openWeb(serverOptions as unknown as Index.ServerData)
  }
}
